<template>
  <div>
    <el-upload
      :action="UPLOAD_URL"
      :file-list="values"
      :multiple="true"
      :headers="getHeaders()"
      :on-success="onXdUploadSuccess"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      accept="image/*"
      list-type="picture-card">
      <i class="el-icon-plus"/>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
      <div class="text-center">
        <img :src="dialogImageUrl" alt="" style="max-width:100%;">
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'XdUpload',

  model: {
    prop: 'imgSrcs',
    event: 'change'
  },
  props: {
    imgSrcs: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // fileList: [],
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  computed: {
    values() {
      if (this.imgSrcs) {
        const data = this.imgSrcs.split(',').map(el => {
          return {
            name: '',
            url: this.imgUrl(el)
          }
        })
        return data
      } else {
        return []
      }
    }
  },
  methods: {
    onXdUploadSuccess(e, file, fileList) {
      debugger;
      if (fileList.some(el => el.percentage !== 100)) {
        return
      }
      
      this.$emit('change', fileList.map(el => el.response.data).join(','))
    },
    handleRemove(file, fileList) {
      this.$emit('change', fileList.map(el => el.response.data).join(','))
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>
